package cn.zyx.org.service.impl;

import cn.zyx.basic.service.impl.BaseServiceImpl;
import cn.zyx.basic.util.PageList;
import cn.zyx.org.domain.Department;
import cn.zyx.org.mapper.DepartmentMapper;
import cn.zyx.org.query.DepartmentQuery;
import cn.zyx.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)  // 加上事务
public class DepartmentServiceImpl extends BaseServiceImpl<Department>
        implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void add(Department department) {
        super.add(department);
        this.update(department);
    }

    @Override
    public void update(Department department) {
        // 如果用户没有选择父部门，那么传过来的department对象中的父部门就为空，即自己就是一级部门，dirPath就是/+自己的id
        if (department.getParent() == null){
            department.setDirPath("/"+ department.getId()); // 这里的id是从数据库里面返回过来的
        }else{ // 如果自己不是第一层级部门
            // 如果自己不是最大部门，应该还要查询出父亲的dirPath+"/"+自己的id
            // 根据父亲的id查询到父亲部门的对象
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            // 获取到父亲的dirPath
            String parentDirPath = parentDept.getDirPath();
            // 拼接自己的dirPath
            String MyDirPath = parentDirPath+"/"+department.getId();
            // 将自己的dirPath赋值给dirPath属性
            department.setDirPath(MyDirPath);
        }
        super.update(department);
    }

    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.loadDeptTree();
    }
}
